package fr.inria.arles.temperatureManagement.queryProcessor.service;

import fr.inria.arles.temperatureManagement.queryProcessor.query.Query;
import java.io.File;
import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.Argument;
import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.control.ActionListener;
import org.cybergarage.upnp.device.InvalidDescriptionException;
import static fr.inria.arles.temperatureManagement.utility.Utility.*;
import static fr.inria.arles.temperatureManagement.Constants.*;

/**
 * Represents the Query Processor UPnP Device
 * @author ajay chhatwal
 */
public class QueryProcessorDevice extends Device implements ActionListener {

    private final static String DESCRIPTION_FILE_NAME =
            "description/description.xml";

    /**
     *
     * Initialises a new Query Processor UPnP Device using its descripton files
     * and adds a it as an UPnP action listner.
     *
     * @throws InvalidDescriptionException if the description file is invalid
     */
    public QueryProcessorDevice() throws InvalidDescriptionException {
        super(new File(DESCRIPTION_FILE_NAME));
        Action requestAction = getAction("ExecuteQuery");
        requestAction.setActionListener(this);
    }

    private String executeQuery(String req) throws Exception {
        String request[] = decode(req);
        Class queryClass = Class.forName(
                "fr.inria.arles.temperatureManagement.queryProcessor.query."
                + request[0]);
        Query query = (Query) queryClass.newInstance();
        return query.execute(request);
    }

    /**
     * Processes the action control recieved by the device.
     * @param action The action whose control is recieved
     * @return true if action is carried out sucessfully,false otherwise.
     */
    public boolean actionControlReceived(Action action) {
        try {
            System.out.println("Action Control Recieved");
            Argument requestArg = action.getArgument(REQUEST_ARG);
            String request = requestArg.getValue();
            String response = executeQuery(request);
            Argument responseArg = action.getArgument(RESPONSE_ARG);
            responseArg.setValue(response);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
